﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Windows;
using Prism.Commands;
using System.Diagnostics;
using Domain;
using System.ComponentModel;
using System.Windows.Input;

namespace EmployeeModule.EmployeeChooser
{
    public class EmployeeChooserController : IEmployeeChooserController
    {
        private IUnityContainer container;
        IEmployeeChooserView view;

        EmployeeChooserViewModel model;

        public EmployeeChooserController(IUnityContainer container, IEmployeeChooserView view)
        {

            this.container = container;
            this.view = view;

            ((UIElement) this.view).CommandBindings.Add(
                new CommandBinding(EmployeeChooserCommands.GetEmployeesByLastNameCommand,
                    GetEmployeesByLastNameExecute));



            model = new EmployeeChooserViewModel();
        }

        public void Show(Action<Employee> ChosenCallback)
        {
            view.SetModel(model);

            // we will show in a popup
            ((Window) view).ShowDialog();

            ChosenCallback(model.SelectedEmployee);
        }

        void GetEmployeesByLastNameExecute(object sender, RoutedEventArgs e)
        {
            string lastname = ((ExecutedRoutedEventArgs)e).Parameter as string;

            EmployeeService svc = new EmployeeService();
            List<Employee> employees = svc.GetEmployees(lastname);

            model.Employees = employees;
        }


        #region viewmodel
        public class EmployeeChooserViewModel : INotifyPropertyChanged
        {
            List<Employee> employees = new List<Employee>();

            public List<Employee> Employees
            {
                get { return employees; }
                set
                {
                    employees = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("Employees"));
                }
            }

            public event PropertyChangedEventHandler PropertyChanged = delegate { };


            private Employee selectedEmployee;

            public Employee SelectedEmployee
            {
                get { return selectedEmployee; }
                set
                {
                    selectedEmployee = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("SelectedEmployee"));
                }
            }
        }

        #endregion

    }
}
